import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import shouye from '@/assets/imgs/aside-img/shouye.png'

const modules = import.meta.glob('./group/*.ts', {
  eager: true,
  import: 'default'
})

export const baseRouter: RouteRecordRaw[] = [{
  path: '',
  redirect: '/home',
  meta: { hidden: true }
}, {
  path: '/redirect',
  component: () => import('@/layout/index.vue'),
  name: 'Redirect',
  children: [{
    path: '/redirect/:path(.*)',
    name: 'Redirect',
    component: () => import('@/views/Redirect/Redirect.vue'),
    meta: { hidden: true }
  }],
  meta: {
    hidden: true
  }
}, {
  path: '/login',
  component: () => import('@/views/login/index.vue'),
  meta: {
    hidden: true
  }
}, {
  path: '/home',
  component: () => import('@/layout/index.vue'),
  meta: {
    title: '首页',
    icon: shouye,
    index: 0
  },
  children: [{
    path: '',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta: { hidden: true }
  }]
}]

export const allRouter: RouteRecordRaw[] = [...baseRouter]

const sortRotuer = <RouteRecordRaw[]>Object.values(modules)

sortRotuer.sort((a, b) => {
  const first = a.meta?.index || Number.MAX_SAFE_INTEGER
  const second = b.meta?.index || Number.MAX_SAFE_INTEGER

  return first - second
})


/** 模块添加name属性 */
sortRotuer.forEach(router => {

  router.name = router.path.replace(/[\/-]\w/g, match => match[1].toLocaleUpperCase())

  if (router.children?.length) {

    router.children.forEach(child => {
      child.name = (router.path + '/' + child.path).replace(/[\/-]\w/g, match => match[1].toLocaleUpperCase())
      child.meta!.parentName = <string>router.name
    })

  }
})

allRouter.push(...sortRotuer)

export const routers = createRouter({
  routes: allRouter,
  history: createWebHashHistory()
})
